import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { Request, Response } from 'express';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  private readonly logger = new Logger(AllExceptionsFilter.name);

  catch(exception: unknown, host: ArgumentsHost): void {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    // 记录详细的错误信息
    this.logger.error('=== 错误详情 ===');
    this.logger.error(`请求方法: ${request.method}`);
    this.logger.error(`请求URL: ${request.url}`);
    this.logger.error(`请求体: ${JSON.stringify(request.body)}`);
    this.logger.error(`查询参数: ${JSON.stringify(request.query)}`);
    this.logger.error(`请求头: ${JSON.stringify(request.headers)}`);

    // 确定错误状态码
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;

    // 获取错误消息
    const message =
      exception instanceof HttpException
        ? exception.getResponse()
        : exception instanceof Error
        ? exception.message
        : '内部服务器错误';

    // 记录错误堆栈
    if (exception instanceof Error) {
      this.logger.error('错误消息:', exception.message);
      this.logger.error('错误堆栈:', exception.stack);
    } else {
      this.logger.error('未知错误:', exception);
    }

    // 记录响应信息
    this.logger.error(`响应状态码: ${status}`);
    this.logger.error('=== 错误详情结束 ===');

    // 发送错误响应
    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      method: request.method,
      message: message,
      ...(process.env.NODE_ENV === 'development' && {
        stack: exception instanceof Error ? exception.stack : undefined,
      }),
    });
  }
} 